/**
 * DataGrid方法类，包括EasyUI DataGrid常用方法
 * create by ck 20160324
 */
function DataGridEvent(){
    this.onLoadSuccess  = function(data){};                     //加载完成事件
    this.onClickRow     = function(rowIndex, rowData){};        //单击行事件
    this.onDblClickRow  = function(rowIndex, rowData){};        //双击行事件
    this.onSelect       = function(rowIndex, rowData){};        //选中事件
    this.onUnselect     = function(rowIndex, rowData){};        //取消选中事件
    this.onSelectAll    = function(rows){};                     //全选事件
    this.onUnselectAll  = function(rows){};                     //取消全选事件
    this.rowStyler      = function(rowIndex, rowData){};        //行样式
    this.onDblClickCell = function(rowIndex, field, value){};   //双击单元格
    this.onSortColumn   = function(sort, order){};
}
var DataGrid = new DataGridEvent();                             //声明DataGrid方法类

$.fn.extend({
    /**
     * 渲染工具栏，添加相应样式后执行渲染
     * 如有回调函数，则在渲染完成后调用
     *
     * @param _callback         --回调函数
     *
     * create by ck 20160912
     * modify by ck 20160926    有回调先覆盖onComplete方法
     */
    parseToolbar: function(_callback){
        if(_callback) $.parser.onComplete = function(){ _callback.call(this); };
        this.find('input[type=text]').each(function(){
            $(this).addClass('easyui-textbox');
        });
        this.find('select').each(function(){
            $(this).addClass('easyui-combobox');
            $(this).attr('editable','false');
            if($(this).children().length <= 8){
                $(this).attr('panelHeight','auto');
            }
        });
        this.find('a').each(function(){
            if($(this).attr('class')) return true;
            $(this).addClass('easyui-linkbutton');
        });
        $.parser.parse(this);
        return this;
    },
    /**
     * 根据url，json，对象初始化表格数据
     * 如果有json.queryParams则添加queryParams参数
     * 如果没有_event则默认DataGrid对象
     *
     * @param _url                  --数据url
     * @param _json                 --json数组
     * @param _event                --对象
     * @returns {initDataGrid}
     *
     * create by ck 20160912
     */
    initDataGrid: function(_url, _json, _event){
        if(!_event) _event = DataGrid;                                      //未定义对象则默认为DataGrid
        var queryParams = {};
        if(_json && _json.queryParams) queryParams = _json.queryParams;     //有json传入且有queryParams
        return this.datagrid({
            url: _url,
            queryParams: queryParams,
            onLoadSuccess: function(data){
                _event.onLoadSuccess(data);
            },
            onClickRow: function(rowIndex, rowData){
                _event.onClickRow(rowIndex, rowData);
            },
            onDblClickRow: function(rowIndex, rowData){
                _event.onDblClickRow(rowIndex, rowData);
            },
            onSelect: function(rowIndex, rowData){
                _event.onSelect(rowIndex, rowData);
            },
            onUnselect: function(rowIndex, rowData){
                _event.onUnselect(rowIndex, rowData);
            },
            onSelectAll: function(rows){
                _event.onSelectAll(rows);
            },
            onUnselectAll: function(rows){
                _event.onUnselectAll(rows);
            },
            rowStyler: function(rowIndex, rowData){
                return _event.rowStyler(rowIndex, rowData);
            },
            onDblClickCell: function(rowIndex, field, value) {
                _event.onDblClickCell(rowIndex, field, value);
            },
            onSortColumn: function(sort, order){
                _event.onSortColumn(sort, order);
            }
        });
    },
    /**
     * 根据是否选中启/禁用按钮
     *
     * @param _no_arr                   --有选中则启用
     * @param _one_arr                  --只选中一个则启用
     * @param _type                     --类型，默认eu
     * @param _event                    --对象
     * @returns {setSelectThenEnable}
     *
     * create by ck 20160912
     */
    setSelectThenEnable: function(_no_arr, _one_arr, _type, _event){
        var target = this;
        if(!_no_arr) _no_arr = [];
        if(!_one_arr) _one_arr = [];
        if(!_type) _type = 'eu';                    //默认easyUI
        if(!_event) _event = DataGrid;              //未定义则默认为DataGrid
        $.each(_no_arr, function(_name, _value){
            $('#'+_value).setButtonDisable(_type);
        });
        $.each(_one_arr, function(_name, _value){
            $('#'+_value).setButtonDisable(_type);
        });
        _event.onSelect = function(){
            $.each(_no_arr, function(_name, _value){
                $('#'+_value).setButtonEnable(_type);
            });
            var _rows = target.datagrid('getSelections');
            if(_rows.length == 1){
                $.each(_one_arr, function(_name, _value){
                    $('#'+_value).setButtonEnable(_type);
                });
            } else{
                $.each(_one_arr, function(_name, _value){
                    $('#'+_value).setButtonDisable(_type);
                });
            }
        };
        _event.onUnselect = function(){
            var _rows = target.datagrid('getSelections');
            if(_rows.length == 0 ){
                $.each(_no_arr, function (_name, _value) {
                    $('#'+_value).setButtonDisable(_type);
                });
            }
            if(_rows.length == 1){
                $.each(_one_arr, function(_name, _value){
                    $('#'+_value).setButtonEnable(_type);
                });
            }
            else{
                $.each(_one_arr, function(_name, _value){
                    $('#'+_value).setButtonDisable(_type);
                });
            }
        };
        _event.onSelectAll = function(){
            $.each(_no_arr, function (_name, _value) {
                $('#'+_value).setButtonEnable(_type);
            });
            var _rows = target.datagrid('getSelections');
            if(_rows.length == 1){
                $.each(_one_arr, function(_name, _value){
                    $('#'+_value).setButtonEnable(_type);
                });
            }
            else{
                $.each(_one_arr, function(_name, _value){
                    $('#'+_value).setButtonDisable(_type);
                });
            }
        };
        _event.onUnselectAll = function(){
            $.each(_no_arr, function (_name, _value) {
                $('#'+_value).setButtonDisable(_type);
            });
            var _rows = target.datagrid('getSelections');
            if(_rows.length == 1){
                $.each(_one_arr, function(_name, _value){
                    $('#'+_value).setButtonEnable(_type);
                });
            }
            else{
                $.each(_one_arr, function(_name, _value){
                    $('#'+_value).setButtonDisable(_type);
                });
            }
        };
        return this;
    },
    /**
     * 刷新表格
     *
     * @returns {dataGridReload}
     *
     * create by ck 20160912
     */
    dataGridReload: function(){
        var list = this;
        window.setTimeout(function() {
            list.datagrid('reload').datagrid('clearSelections');
        }, 100);
        return this;
    },
    /**
     * 清除选中
     *
     * @returns {dataGridClear}
     *
     * create by ck 20160912
     */
    dataGridClear: function(){
        return this.datagrid('clearSelections');
    },
    /**
     * 表格添加参数
     *
     * @param _json
     * @returns {addDataGridParams}
     *
     * create by ck 20160912
     */
    addDataGridParams: function(_json){
        return this.datagrid('load', _json);
    },
    /**
     * 合并行显示
     *
     * @param ColArray
     *
     * create by ck 20160912
     */
    mergeCellsByField: function(ColArray) {
        //var ColArray = colList.split('');
        var TableRowCnts = this.datagrid('getRows').length;
        var tmpA;
        var tmpB;
        var PerTxt = "";
        var CurTxt = "";
        var alertStr = "";
        for (j = ColArray.length - 1; j >= 0; j--) {
            PerTxt = "";
            tmpA = 1;
            tmpB = 0;

            for (i = 0; i <= TableRowCnts; i++) {
                if (i == TableRowCnts) {
                    CurTxt = "";
                }
                else {
                    CurTxt = this.datagrid('getRows')[i][ColArray[j]];
                }
                if (PerTxt == CurTxt) {
                    tmpA += 1;
                }
                else {
                    tmpB += tmpA;
                    this.datagrid('mergeCells', {
                        index: i - tmpA,
                        field: ColArray[j],　　//合并字段
                        rowspan: tmpA,
                        colspan: null
                    });
                    this.datagrid('mergeCells', { //根据ColArray[j]进行合并
                        index: i - tmpA,
                        field: 'Ideparture',
                        rowspan: tmpA,
                        colspan: null
                    });

                    tmpA = 1;
                }
                PerTxt = CurTxt;
            }
        }
        return this;
    },
    /**
     * 渲染目标对象内的表单对象
     * 如有selector对象，则必填的完成后激活，否则禁用
     *
     * @param _selector
     * @returns {parseForm}
     *
     * create by ck 20160912
     */
    parseForm: function(_selector){
        //按钮，文本框，下拉框添加class样式
        this.find('select,textarea,:text,:password,:file,input[type=number],input[type=datetime],input[type=time],input[type=date]').each(function(){
            $(this).addClass('form-control');
        });
        //a标签，重置按钮添加class样式
        this.find('a,:reset,:button,:submit').each(function(){
            $(this).addClass('btn btn-default');
        });
        //表格中textarea元素的父元素的前一个兄弟元素顶端对齐
        this.find('table td textarea').parent().prev().css({
            "vertical-align": "top",
            "padding-top": "10px"
        });
        //对table的表单中必填的项目添加文字及样式并绑定事件
        var mustDom = this.find('[must=true]');
        var check;
        mustDom.each(function () {
            $(this).attr('placeholder','必填');
            $(this).parent().addClass('has-warning');
        });
        mustDom.on('change keyup', function(){
            if($(this).val() != '') $(this).parent().removeClass('has-warning').addClass('has-success');
            else $(this).parent().removeClass('has-success').addClass('has-warning');
            if(_selector){
                check = true;
                mustDom.each(function(){
                    if($(this).val() == '') check = false;
                });
                if(check) _selector.removeClass('disabled');
                else _selector.addClass('disabled');
            }
        });
        return this;
    },
    /**
     * 重置表单
     * 将文本框，多行文本框置空，下拉框置为第一个选项
     *
     * @returns {resetForm}
     *
     * create by ck 20160912
     */
    resetForm: function(){
        this.find(':text,:password,input[type=number],input[type=date]').attr('value','').val('');           //清空文本框内容
        this.find('textarea').text('').val('');                                             //清空textarea内容
        this.find('select').prop('selectedIndex', 0);                                       //下拉框选值第一个
        return this;
    },
    /**
     * 根据按钮类型启用按钮
     *
     * @param _type
     * @returns {setButtonEnable}
     *
     * create by ck 20160912
     */
    setButtonEnable: function(_type){
        if(_type == 'eu') this.linkbutton('enable');
        else if(_type == 'bs') this.removeClass('disabled');
        return this;
    },
    /**
     * 根据按钮类型禁用按钮
     *
     * @param _type
     * @returns {setButtonEnable}
     *
     * create by ck 20160912
     */
    setButtonDisable: function(_type){
        if(_type == 'eu') this.linkbutton('disable');
        else if(_type == 'bs') this.addClass('disabled');
        return this;
    },
    /**
     * 根据字段名返回选中行的字段值
     *
     * @param _field
     * @returns {Object}
     *
     * create by ck 20160912
     * modify by ck 20170316    增加无选中返回null判断
     */
    getDataGridSelectedField: function(_field){
        var _row = this.datagrid('getSelected');
        return _row ? eval('_row.'+_field) : '';
    },
    /**
     * 根据字段名返回所有选中行的字段值
     * 以逗号隔开
     *
     * @param _field
     * @param _array
     * @returns {string}
     *
     * create by ck 20160912
     * modify by ck 20170811    添加参数可返回数组
     */
    getDataGridSelectedFields: function(_field, _array){
        var _rows = this.datagrid('getSelections');
        var _ids = [];
        var _tmp;
        for(var i=0; i<_rows.length; i++){
            _tmp = eval('_rows['+i+'].'+_field);
            // if(_tmp){
                _ids.push(_tmp);
            // }
        }
        return _array ? _ids : _ids.join(',');
    },
    /**
     * 检查easyui按钮是否被禁用
     * 禁用则返回true
     *
     * @returns {*}
     *
     * create by ck 20160912
     */
    checkButtonDisabled: function(){
        return this.linkbutton('options').disabled;
    },
    /**
     * 根据元素类型获取easyui元素的值
     *
     * @param _multiple
     * @returns {*|{js, css, dependencies}}
     *
     * create by ck 20160912
     * modify by ck 20161101    如为多选，则下拉框返回数组
     */
    getElementValue: function(_multiple){
        if(this.length <= 0) return '';
        var _tag_name = this[0].tagName;
        switch (_tag_name.toLowerCase()){
            case 'select': {
                return this.combobox(_multiple ? 'getValues' : 'getValue');
            } break;
            case 'input' : return this.textbox('getText');  break;
        }
    },
    /**
     * 关闭所有标签
     *
     * @returns {closeAllTab}
     *
     * create by ck 20161009
     */
    closeAllTab: function(){
        var allTabs = this.tabs('tabs');
        var allTabtitle = [];
        $.each(allTabs, function (i, n) {
            var opt = $(n).panel('options');
            allTabtitle.push(opt.title);
        });
        for (var i = 0; i < allTabtitle.length; i++) {
            this.tabs('close', allTabtitle[i]);
        }
        return this;
    }
});

/**
 * 根据传入信息，创建modal并打开
 * 确认按钮id为bt_modal_confirm
 *
 * @param _content      --内容
 * @param _title        --标题
 * @param _button_text  --按钮文本
 * @param _size         --大小
 * @param _callback     --回调函数
 * @param _callJson     --回调参数
 * @constructor
 *
 * create by ck 20160324
 * modify by ck 20160901    结构更改，精简
 * modify by ck 20160907    增加回调函数，调用处于激活状态的iframe中的方法
 */
//function createModal(_content, _title, _button_text, _size, _callback, _callJson){
//    var modal = $('#XHManage_Modal');
//    if(modal.length > 0){                                                            //如果存在则删除
//        $('.modal-backdrop').filter('.fade').filter('.in').remove();                 //去除遮罩层
//        modal.modal('hide').remove();                                                //隐藏并删除
//    }
//    var modalStr = '<div class="modal fade' + (_size == 'sm' ? ' bs-example-modal-sm' : (_size == 'lg' ? ' bs-example-modal-lg' : '')) + '" id="XHManage_Modal">'
//        + '<div class="modal-dialog' + (_size == 'sm' ? ' modal-sm' : (_size == 'lg' ? ' modal-lg' : '')) + '">';
//    modalStr += '<div class="modal-content">';
//    modalStr +=     '<div class="modal-header">';
//    modalStr +=         '<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>';
//    modalStr +=         '<h4 class="modal-title">' + (_title ? _title : '提示') + '</h4>';
//    modalStr +=     '</div>';
//    if(_content){
//        modalStr +=     '<div class="modal-body">';
//        modalStr +=         _content;
//        modalStr +=     '</div>';
//    }
//    if(_button_text){
//        modalStr += '<div class="modal-footer">';
//        modalStr +=     '<button type="button" class="btn btn-primary" id="bt_modal_confirm">'+_button_text+'</button>';
//        modalStr +=     '<button type="button" class="btn btn-default" data-dismiss="modal" id="bt_modal_close">关闭</button>';
//        modalStr +=  '</div>';
//    }
//    modalStr += '</div>';
//    modalStr += '</div>';
//    modalStr += '</div>';
//    $(document.body).append(modalStr).find('#XHManage_Modal').modal('show');
//    if(_callback) _callback.call(this, _callJson);
//}